3-2 实现User微服务健康检查:GPRCHealth完整集成
服务端 HealthController 实现
在 user 微服务中创建 HealthController,响应 gRPC 健康检查请求:
// src/health/health.controller.ts
import { Controller } from '@nestjs/common';
import { HealthServiceControllerMethods } from '@remote/proto-pkg';
@Controller()
@HealthServiceControllerMethods()
export class HealthController {
check(data: { service: string }) {
// 返回 status = 1 表示服务健康
return { status: 1 };
}
}
typescript
响应状态码定义
| 状态码 | 含义 | 说明 |
|---|---|---|
| 1 | SERVING | 服务正常运行 |
| 2 | NOT_SERVING | 服务不可用 |
| 3 | SERVICE_UNKNOWN | 未知服务 |
HealthModule 配置
// src/health/health.module.ts
import { Module } from '@nestjs/common';
import { HealthController } from './health.controller';
@Module({
controllers: [HealthController],
})
export class HealthModule {}
typescript
在 AppModule 中导入:
@Module({
imports: [HealthModule],
})
export class AppModule {}
typescript
完整集成流程
1. proto-pkg 中定义 health.proto(公共)
2. user 微服务的 user.proto 引入 health.proto
3. 代码生成 → HealthServiceControllerMethods 和相关类型
4. 创建 HealthController 实现 check 方法
5. 创建 HealthModule 注册 Controller
6. AppModule 导入 HealthModule
7. main.ts 改为纯 gRPC 模式(去掉 RESTful 端口)
text
入口文件 main.ts
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';
import { join } from 'path';
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>({
transport: Transport.GRPC,
options: {
package: ['user', 'health'],
protoPath: join(__dirname, '../node_modules/@remote/proto-pkg/proto/user.proto'),
url: '0.0.0.0:40001',
},
});
await app.listen();
}
bootstrap();
typescript
使用 grpcurl 验证
安装 grpcurl 工具后,可以直接测试健康检查接口:
# 安装 grpcurl
brew install grpcurl
# 测试 user 微服务健康检查
grpcurl -plaintext \
-d '{"service": "user"}' \
localhost:40001 \
health.HealthService/Check
# 预期响应
{
"status": 1
}
bash
grpcurl 常用命令
| 命令 | 说明 |
|---|---|
grpcurl -plaintext localhost:40001 list | 列出所有服务 |
grpcurl -plaintext localhost:40001 list health.HealthService | 列出服务方法 |
grpcurl -plaintext -d '{}' localhost:40001 health.HealthService/Check | 调用 Check 方法 |
服务注册与 Consul 健康检查
目前 Consul 注册仍使用 HTTP 健康检查。gRPC 健康检查的直接好处是:
- 节省端口:不再需要额外的 RESTful 端口
- 协议统一:全链路使用 gRPC 协议
- 标准规范:遵循 gRPC Health Checking Protocol 标准
后续可以通过 Gateway 统一暴露健康检查端点(详见 3-4 节)。
参考资源
- gRPC Health Checking Protocol - 健康检查协议规范
- grpcurl - gRPC 命令行测试工具
- NestJS gRPC - NestJS gRPC 文档
↑